package org.edu.modules.act.controller;
import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import groovy.util.logging.Slf4j;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.edu.common.api.vo.Result;
import org.edu.common.aspect.annotation.AutoLog;
import org.edu.common.system.vo.LoginUser;
import org.edu.modules.act.entity.ActReWordModel;
import org.edu.modules.act.mapper.ActReWordModelMapper;
import org.edu.modules.act.mapper.ActRuInstanceFileMapper;
import org.edu.modules.act.service.WordOnlineService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Api(tags = "我的日程安排")
@RestController
@RequestMapping("activiti/word")
@Slf4j
public class ProcessFileController {

    @Resource
    private OSS ossClient;

    @Resource
    private ActReWordModelMapper actReWordModelMapper;

    @Resource
    private WordOnlineService wordOnlineService;

    // 日志注解
    @AutoLog(value = "流程设计-word模板")
    @ApiOperation(value = "流程设计", notes = "流程设计-word模板")
    // 上传wrod模板
    @PostMapping(value = "/uploadWordModel")
    public Result<?> uploadWordModel(MultipartFile file, String modelId) {
        String fileName = null;
        String suffixName = null;
        String h5=null;
        if (file != null) {
            //myFile为MultipartFile类型
//            CommonsMultipartFile cf= (CommonsMultipartFile)file;
//            DiskFileItem fi = (DiskFileItem)cf.getFileItem();
//            File document = fi.getStoreLocation();
            //把MultipartFile文件流转换成文件
            File document = null;
            //获取文件名
            fileName = file.getOriginalFilename();
            //用点来切割获取文件类型注意//.需要加双斜杠正则表达式
            String[] arr = fileName.split("\\.");
            //获取文件后缀名
            suffixName = arr[arr.length - 1];
            if (!suffixName.equalsIgnoreCase("doc") && !suffixName.equalsIgnoreCase("docx")
            ) {
                return Result.error(400, "不支持word以外的文件上传");
            }
            try {
                String originalFilename = file.getOriginalFilename();
                String[] filename = originalFilename.split("\\.");
                if (filename[0].length()>3){
                    document = File.createTempFile(filename[0], filename[1]);
                }else {
                    document = File.createTempFile(filename[0] + "123", filename[1]);
                }
                file.transferTo(document);
                document.deleteOnExit();
            } catch (IOException e) {
                e.printStackTrace();
            }
            //获取文件长度
            Long size = file.getSize();
            //获取唯一的文件名称
            String docName = UUID.randomUUID().toString() + "." + suffixName;
            //上传文件到指定的存储空间  第一个参数 bucketName  第二个参数 OSS存储路径  第三个参数 要上传的文件
            PutObjectResult result = ossClient.putObject("digital-school-xx0422", "school-demo/" + docName, document);
            //文件下载地址
            String path = "https://digital-school-xx0422.oss-cn-shenzhen.aliyuncs.com/school-demo/" + docName;
            System.out.println("-----------文件下载地址-------" + path);


            QueryWrapper<ActReWordModel> wrapper = new QueryWrapper();
            wrapper.eq("MODEL_ID", modelId);
            List<ActReWordModel> list = actReWordModelMapper.selectList(wrapper);

            if (list.size() == 0) {
                //如果word表格没有改modelId对应的记录，则插入一条数据
                ActReWordModel actReWordModelEntity = new ActReWordModel();
                actReWordModelEntity.setModelId(modelId);
                actReWordModelEntity.setWordFileUrl(path);
                actReWordModelEntity.setTerminalId(1);
                actReWordModelEntity.setFileName(fileName);
                //获取redis里缓存的用户
                LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
                actReWordModelEntity.setUserId(user.getId());

                //插入单据模板的表
                actReWordModelMapper.insert(actReWordModelEntity);
            } else {
                //如果word已经存在，则覆盖url
                ActReWordModel actReWordModelEntity = new ActReWordModel();
                actReWordModelEntity.setId(list.get(0).getId());
                actReWordModelEntity.setWordFileUrl(path);
                actReWordModelEntity.setFileName(fileName);
                actReWordModelMapper.updateById(actReWordModelEntity);
            }

            Map<String, String> map=null;
            try {
                map= wordOnlineService.getH5(path);
            } catch (Exception e) {
                e.printStackTrace();
            }

            h5=map.get("h5");

        }
        return Result.OK(h5);
    }

    // 日志注解
    @AutoLog(value = "流程word上传-转换为了编辑器格式的H5")
    @ApiOperation(value = "流程word上传", notes = "流程word上传-转换为了编辑器格式的H5")
    // 上传wrod模板
    @PostMapping(value = "/changeH5")
    public Result<?> changeH5(String newH5,String modelId){
        QueryWrapper<ActReWordModel> wrapper = new QueryWrapper();
        wrapper.eq("MODEL_ID", modelId);
        List<ActReWordModel> list = actReWordModelMapper.selectList(wrapper);
        ActReWordModel ActReWordModel = new ActReWordModel();
        ActReWordModel.setId(list.get(0).getId());
        ActReWordModel.setWordH5(newH5);
        actReWordModelMapper.updateById(ActReWordModel);
        return Result.OK();
    }

}
